//
//  YAYIPatientViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/24.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIPatientViewController.h"
#import "YAYISerachResultController.h"
#import "YAYITagGroupViewController.h"
#import "YAYIPatientComeController.h"
#import "YAYILoginViewController.h"
#import "YAYIAddressBookViewController.h"

#import "YAYIPatientCell.h"
#import "YAYIPatientHeaderCell.h"
#import "YAYIMyPatientItem.h"
#import "YAYIMyPatientTool.h"
#import "UITabBar+badge.h"

@interface YAYIPatientViewController () <UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, YAYIPatientComeControllerDelegate>

//@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableViewController *searchResultsController;
@property (nonatomic, weak) UISearchBar *searchBar;


@property (nonatomic, strong) NSMutableArray *firstSectionRowArry;
// 模拟网络数据
@property (nonatomic, strong) NSArray  *serverDataArr;//数据源

@property (nonatomic, strong) NSMutableArray *patientArray;

@property (nonatomic, strong) NSArray *sectionArray;//row arr
@property (nonatomic, strong) NSArray *sectionTitleArray;//section arr
@property (nonatomic, strong) NSMutableArray *searchResultArr;

// 是否执行过搜索
@property (nonatomic, assign) BOOL isSearched;

@property (nonatomic, weak) YAYISerachResultController *resultVc;

@end

@implementation YAYIPatientViewController


- (NSMutableArray *)searchResultArr
{
    if (nil == _searchResultArr) {
        _searchResultArr = [NSMutableArray array];
    }
    return _searchResultArr;
}

- (NSMutableArray *)firstSectionRowArry
{
    if (nil == _firstSectionRowArry) {
        
        _firstSectionRowArry = [NSMutableArray array];
        YAYIPatientHeaderItem *model1 = [[YAYIPatientHeaderItem alloc] init];
        model1.name = @"新的患者";
        model1.iconName = @"patient_headIcon1";
        
//        YAYIPatientHeaderItem *model2 = [[YAYIPatientHeaderItem alloc] init];
//        model2.name = @"从通讯录导入";
//        model2.iconName = @"patient_headIcon2";
        
        YAYIPatientHeaderItem *model3 = [[YAYIPatientHeaderItem alloc] init];
        model3.name = @"标签分组（0）";
        model3.iconName = @"patient_headIcon3";
        
        [_firstSectionRowArry addObjectsFromArray:@[model1, model3]];
    }
    return _firstSectionRowArry;
}

- (NSMutableArray *)patientArray
{
    if (nil == _patientArray) {
        _patientArray = [NSMutableArray array];
    }
    return _patientArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的患者";
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor darkGrayColor];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    self.tableView.sectionFooterHeight = 0;
    
//    [self.set];
    [self setModelData];
    
    [self setupSearchController];
    
//    [self createDataSource];
    
    // 当登录状态改变刷新页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStateChanged:) name:YAYILoginNotifyName object:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self getTagCount];
    [self getBadgeState];
    [self getMyPatients];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}


//- (instancetype)initWithStyle:(UITableViewStyle)style
//{
////    return [super initWithStyle:UITableViewStyleGrouped];
//}

//加载搜索框
-(void)setupSearchController{

    UISearchBar *searchBar = [[UISearchBar alloc] init];
    NSArray *subViews;
    subViews = [(searchBar.subviews[0]) subviews];
    for (id view in subViews)
    {
        if ([view isKindOfClass:[UIButton class]])
        {
            UIButton* cancelbutton = (UIButton* )view;
            [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [cancelbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
            break;
        }
    }
    
    searchBar.tintColor = [UIColor grayColor];
    searchBar.frame = CGRectMake(0, 0, SCREEN_width, 44);
    [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex : 0] removeFromSuperview];
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.searchBar = searchBar;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 44)];
    [view addSubview:searchBar];
     self.tableView.tableHeaderView = view;
    
}


/**
 *  字典转模型
 */
- (void)setModelData
{
    for (NSDictionary *dict in self.serverDataArr)
    {
        YAYIMyPatientItem *model = [[YAYIMyPatientItem alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [self.patientArray addObject:model];
    }
    
    _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
    YAYILog(@"_sectionArray:%@", _sectionArray);
    
    _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
    YAYILog(@"_sectionArr:%@", _sectionTitleArray);
}


/**
 *  设置患者报道 及 标签分组的数量
 */
- (void)setReportCont:(NSInteger)reportCount andTagCount:(NSInteger)tagCount
{
    YAYILog(@"reportCount:%ld tagCount:%ld", reportCount, tagCount);
    // 患者报道数量数量
    // 标签分组数量
    YAYIPatientHeaderItem *model1 = self.firstSectionRowArry[0];
    model1.badgeValue = reportCount;
    
    // 标签分组数量
    YAYIPatientHeaderItem *model2 = self.firstSectionRowArry[1];
    model2.name = [NSString stringWithFormat:@"标签分组（%ld）", tagCount];
    
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath1, indexPath2] withRowAnimation:UITableViewRowAnimationNone];
}


- (void)loginStateChanged:(NSNotification *)notify
{
    YAYILog(@"notify:%@", notify);
    
    // 刷新表格
    [self createDataSource];
}


#pragma mark - 获取数据
- (void)getMyPatients
{
    
    [self.patientArray removeAllObjects];
    
    [YAYINetWorking getWithURL:patienList_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
                _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
            }else{
                
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYIMyPatientItem *item = [YAYIMyPatientItem new];
                    [item setValuesForKeysWithDictionary:obj];
                    
                    [self.patientArray addObject:item];
                }
                
                _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
                YAYILog(@"_sectionArray:%@", _sectionArray);
                
                _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
                YAYILog(@"_sectionArr:%@", _sectionTitleArray);
            }
            
            [self.tableView reloadData];
            
            
            //            if (0 == self.appointArray.count) {
            //                [self showNoDataFlag:YES];
            //
            //            }else{
            //                [self showNoDataFlag:NO];
            //            }
        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
}


- (void)createDataSource
{
    // 显示hud
    [SVProgressHUD show];
    
    [self getMyPatients];
}


- (void)getTagCount
{
    [self.patientArray removeAllObjects];
    
    [YAYINetWorking getWithURL:patienTagNum_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                NSInteger bdNum = 0;
                NSInteger tagNum = 0;
                
                [self setReportCont:bdNum andTagCount:tagNum];
            }else{
                
                NSInteger bdNum = [dict[@"map"][@"bdNum"] integerValue];
                NSInteger tagNum = [dict[@"map"][@"tagNum"] integerValue];
                
                [self setReportCont:bdNum andTagCount:tagNum];
            }

        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
    
}

/**
 *  获取小红点显示状态
 */
- (void)getBadgeState
{
    
    [YAYINetWorking getWithURL:queryMsg_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSArray *dataArray = dict[@"data"];
                if (dataArray.count > 0) {
                    
                    NSInteger newPatientMsg = [dataArray[0][@"hasnew"] integerValue];
                    if (newPatientMsg > 0) {
                        [self.tabBarController.tabBar showBadgeOnItemIndex:1];
                    }else{
                        [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
                    }
                }
            }
        }else{
            
            YAYILog(@"erro:%@", error);
        }
    }];
}


/**
 *  未读消息清零
 */
- (void)clearBadgeState
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"type"] = @(1);
    [YAYINetWorking postJsonSerilizeWithURL:updateMsg_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
            }
        }else{
            
            YAYILog(@"erro:%@", responseError);
        }
    }];
}


- (void)getSearchResultBy:(NSString *)keyWord
{
    // 显示hud
    
    [self.searchResultArr removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"key"] = keyWord;
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking getWithURL:patienList_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYIMyPatientItem *item = [YAYIMyPatientItem new];
                    [item setValuesForKeysWithDictionary:obj];
                    
                    [self.searchResultArr addObject:item];
                }
                
                [self.tableView reloadData];
            }

        }else{
            
            YAYILog(@"erro:%@", error);
        }

    }];
    
}


#pragma mark - 工具方法
- (void)filterContentForSearchText:(NSString*)searchText
{
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    
    [self.searchResultArr removeAllObjects];
    for (int i = 0; i < self.patientArray.count; i++) {
        YAYIMyPatientItem *model = self.patientArray[i];
        NSString *nameStr = model.clientname;
        NSString *pinyinStr = model.pinyin;
        
        NSRange nameRange = [nameStr rangeOfString:searchText options:searchOptions];
        NSRange pinyinRange = [pinyinStr rangeOfString:searchText options:searchOptions];
        
        
        if (nameRange.length || pinyinRange.length)
        {
            [self.searchResultArr addObject:model];
        }
        
    }
    
    YAYILog(@"self.searchResultArr:%@", self.searchResultArr);
}


#pragma mark - 代理方法
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 判断是否进行了搜索
    if (self.isSearched) {
        return 0;
    }
    
    if (0 == section) {
        return 0;
    }
    return 22.0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14.5f]];
        
        [label setTextColor:[UIColor grayColor]];
        [label setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
    }
    
    [label setText:[NSString stringWithFormat:@"  %@",self.sectionTitleArray[section]]];
    
    return label;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // 判断是否进行了搜索
    if (self.isSearched) {
        return 1;
    }
    
    return _sectionArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 判断是否进行了搜索
    if (self.isSearched) {
        return self.searchResultArr.count;
    }
    
    if (0 == section) {
        return 2;
    }

    return [self.sectionArray[section - 1]  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 50.0;
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    // 判断是否进行了搜索
    if (self.isSearched) {
        return nil;
    }
    return self.sectionTitleArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index - 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 判断是否进行了搜索
    if (self.isSearched) {
        YAYIPatientCell *cell = [YAYIPatientCell cellWith:tableView];
        
        YAYIMyPatientItem *model = self.searchResultArr[indexPath.row];
        cell.item = model;
        return cell;
    }
    
    if (0 == indexPath.section) {

        YAYIPatientHeaderCell *cell = [YAYIPatientHeaderCell cellWith:tableView];
        
        YAYIPatientHeaderItem *model = self.firstSectionRowArry[indexPath.row];
        cell.item = model;
        
        if (indexPath.row == 0) {
            cell.lineType = LineTypeTopAndBottom;
        }else{
            cell.lineType = LineTypeBottom;
        }
        
        return cell;
    }
    
    YAYIPatientCell *cell = [YAYIPatientCell cellWith:tableView];
    
    YAYIMyPatientItem *model = self.sectionArray[indexPath.section - 1][indexPath.row];
    cell.item = model;
    [cell setCenterLine];
    
    // 判断使用什么线
    if (indexPath.row == 0) {
        cell.lineType = LineTypeTop;
    }else if (indexPath.row == [self.sectionArray[indexPath.section - 1] count] - 1){
        cell.lineType = LineTypeBottom;
    }else{
        cell.lineType = LineTypeCenter;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isSearched) {
        return;
    }
    
    if (0 == indexPath.section && 0 == indexPath.row) { // 新的患者
        
        YAYIPatientComeController *come = [YAYIPatientComeController new];
        come.title = @"患者报到";
        come.delegate = self;
        [self.navigationController pushViewController:come animated:YES];
        
        // 将消息清零（小红点）
        [self clearBadgeState];
        
    }else if (0 == indexPath.section && 1 == indexPath.row){ // 标签分组
        
        YAYITagGroupViewController *tagVc = [[YAYITagGroupViewController alloc] init];
        [self.navigationController pushViewController:tagVc animated:YES];
    }else{
    
//        YAYIMyPatientItem *model = self.sectionArray[indexPath.section - 1][indexPath.row];
//        YAYILog(@"model.mobile:%@", model.mobile);
//        
//        YWPerson *person = [[YWPerson alloc] initWithPersonId:model.mobile appKey:YAYIPatientIMAppKey];
//        YWConversation *conversation=[YWP2PConversation fetchConversationByPerson:person creatIfNotExist:YES baseContext:[SPKitExample sharedInstance].ywIMKit.IMCore];
//        YWConversationViewController *conversationController = [[SPKitExample sharedInstance].ywIMKit makeConversationViewControllerWithConversationId:conversation.conversationId];
//        
//        [self.navigationController pushViewController:conversationController animated:YES];
//        [SVProgressHUD showImage:nil status:@"建设中..."];
    }
}

#pragma  mark searchController delgate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;{
    //    NSString *filterString = searchController.searchBar.text;
    //
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", filterString];
    //    self.searchArry = [NSMutableArray arrayWithArray:[self.tableArry filteredArrayUsingPredicate:predicate]];
    //    //    UITableViewController *searchTableController=(UITableViewController *)searchController;
    //    [self.searchResultsController.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController
{
    self.tabBarController.tabBar.hidden = YES;
}


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
//    self.tabBarController.tabBar.hidden = YES;
//    self.navigationController.navigationBar.hidden = YES;

    
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //取消
    [searchBar resignFirstResponder];

//    [self.tableView reloadData];
}


- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    self.isSearched = NO;
    searchBar.text = nil;
    [searchBar setShowsCancelButton:NO animated:YES];
    
    [self.tableView reloadData];
    return YES;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    YAYILog(@"searchBar.text:%@", searchBar.text);
    if (searchBar.text.length == 0) {
        [searchBar resignFirstResponder];
        [searchBar setShowsCancelButton:NO animated:YES];
        self.isSearched = NO;
        
//        [self.tableView reloadData];
    }else{
    
        self.isSearched = YES;
        
//        [self getSearchResultBy:searchBar.text];
        [self filterContentForSearchText:searchBar.text];
        
        [self.tableView reloadData];
    }
    
}


#pragma - mark YAYIPatientComeControllerDelegate
- (void)patientComeControllerAccepted
{
    [self getMyPatients];
    
}



@end
